package cn.stylefeng.guns.modular.packreview.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.modular.packreview.entity.PackReview;
import cn.stylefeng.guns.modular.packreview.entity.PackReviewExcelItem;
import cn.stylefeng.guns.modular.packreview.entity.PickingList;
import cn.stylefeng.guns.modular.packreview.entity.PickingListExcelItem;
import cn.stylefeng.guns.modular.packreview.mapper.PickingListMapper;
import cn.stylefeng.guns.modular.packreview.model.params.PackReviewDetailsParam;
import cn.stylefeng.guns.modular.packreview.model.params.PackReviewParam;
import cn.stylefeng.guns.modular.packreview.model.params.PickingListParam;
import cn.stylefeng.guns.modular.packreview.model.result.PickingListResult;
import  cn.stylefeng.guns.modular.packreview.service.PickingListService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.stylefeng.guns.modular.location.excel.ExcelUtils.getCellValue;
import static cn.stylefeng.guns.sys.core.shiro.ShiroKit.getUser;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wp
 * @since 2025-07-26
 */
@Service
public class PickingListServiceImpl extends ServiceImpl<PickingListMapper, PickingList> implements PickingListService {

    @Override
    public void add(PickingListParam param){
        PickingList entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(PickingListParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(PickingListParam param){
        PickingList oldEntity = getOldEntity(param);
        PickingList newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public PickingListResult findBySpec(PickingListParam param){
        return null;
    }

    @Override
    public List<PickingListResult> findListBySpec(PickingListParam param){
        return this.baseMapper.customListNew(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(PickingListParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData getExceldata(MultipartFile file, PickingListParam pickingListParam, ResponseData data) throws IOException {

        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        List<PickingListExcelItem> list = new ArrayList<PickingListExcelItem>();
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            PickingListExcelItem pickingListExcelItem = new PickingListExcelItem();
            String pickNumber = getCellValue(row.getCell(0));//拣选单编码
            if (ToolUtil.isEmpty(pickNumber)) {
                return ResponseData.error("第"+r+"行拣选单编码不能为空");
            }
            if (!pickNumber.contains("PKTNA")){
                return ResponseData.error("第"+r+"行拣选单编码格式不正确: 必须以PKTNA开头");
            }
            pickingListExcelItem.setPickNumber(pickNumber);

            String pickType = getCellValue(row.getCell(1));//拣选单类型
            pickingListExcelItem.setPickType(pickType);

            String pickTime = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(2));//创建时间
            pickingListExcelItem.setPickTime(pickTime);

            String skuCount = getCellValue(row.getCell(3));//拣选品种数(商品的SKU数)
            pickingListExcelItem.setSkuCount(skuCount);

            String goodsCount = getCellValue(row.getCell(4));//商品件数
            pickingListExcelItem.setGoodsCount(goodsCount);

            list.add(pickingListExcelItem);
        }

        ShiroUser user = getUser();
        //主表信息
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, PickingListExcelItem> trackNumberMap = list.stream()
                .collect(Collectors.toMap(PickingListExcelItem::getPickNumber, Function.identity(), (existing, replacement) -> existing)); // 使用自定义的合并函数来保持第一个遇到的元素（如果有重复的track number）
        List<PickingListExcelItem> uniqueList = new ArrayList<>(trackNumberMap.values()); // 从Map中提取值列表作为结果列表


        for (PickingListExcelItem pickingListExcelItem : uniqueList) {

            PickingList pickingList = new PickingList();
            BeanUtils.copyProperties(pickingListExcelItem, pickingList);

            pickingList.setPutCustomerId(pickingListParam.getPutCustomerId());
            pickingList.setWarehouseId(pickingListParam.getWarehouseId());
            pickingList.setDeptId(user.getDeptId());
            pickingList.setCreateBy(user.getName());//创建人
            pickingList.setCreateTime(new Date());
            this.baseMapper.insertPickingList(pickingList);
        }

        data.setSuccess(true);
        data.setMessage("导入成功");
        return data;
    }

    @Override
    public String findPickTypeByPickNumber(String pickNumber) {
        return this.baseMapper.findPickTypeByPickNumber(pickNumber);
    }

    private Serializable getKey(PickingListParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private PickingList getOldEntity(PickingListParam param) {
        return this.getById(getKey(param));
    }

    private PickingList getEntity(PickingListParam param) {
        PickingList entity = new PickingList();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
